<?php
/**
 * @Notes by 操作日志表.
 * @author: ysongyang <ysongyang@qq.com>
 * @link
 * @copyright: copyright 2017-03-27 ysongyang all rights reserved.
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */

namespace app\model;

use think\Model;
use think\Request;

class RecordLog extends Model
{

    /**
     * 日志插入
     * @param $user_id
     * @param $msg
     */
    public function insertLog($user_id, $msg)
    {
        $admin_model = new Admin();
        $request = Request::instance();
        $c = $request->controller();
        $m = $request->module();
        $a = $request->action();
        $msg = "账号 " . $admin_model->getUserField($user_id, "username") . " 于 " . date('Y-m-d H:i:s') . " " . $msg;
        $data = [
            'uid' => $user_id,
            'controller' => $c,
            'module' => $m,
            'action' => $a,
            'message' => $msg,
            'type' => 1,
            'ip' => get_client_ip(),
            'record_time' => date('Y-m-d H:i:s')
        ];
        unset($admin_model);
        $this->save($data);
    }

    /**
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getLogList()
    {
        $field = "id,uid,message,type,ip,record_time";
        $map['type'] = ['in', '1,2'];
        $list = $this->field($field)->where($map)->order('id desc')->limit(100)->select();
        foreach ($list as $key => $value) {
            if (!empty($value['uid']) && $value['type']==1) {
                $admin_model = new Admin();
                $list[$key]['user_username'] = $admin_model->getUserField($value['uid'], 'username');
            }
            if (!empty($value['uid']) && $value['type']==2) {
                $user_model = new User();
                $list[$key]['user_username'] = $user_model->getUserField($value['uid'],'username');
            }
            $list[$key]['type'] = $value['type'] == '2' ? "前端" : "后端";
        }
        unset($user_model);
        unset($admin_model);
        return $list;
    }
}